package de.earthquake;

import java.text.SimpleDateFormat;

import model.EarthquakeEntry;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;

import com.google.gson.Gson;

public class EarthquakeDetail extends Fragment {
	
	public static EarthquakeDetail newInstance(EarthquakeEntry entry) {
		EarthquakeDetail f = new EarthquakeDetail();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        Gson gson = new Gson();
        args.putString(CONSTANTS.EARTHQUAKE_JSON, gson.toJson(entry));
        f.setArguments(args);

        return f;
    }

	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_detail, container, false);
		setText(getShownIndex(), view);
		return view;
	}
	
	public EarthquakeEntry getShownIndex() {
		Gson gson = new Gson();
		EarthquakeEntry entry = null;
		if (getArguments() != null && getArguments().getString(CONSTANTS.EARTHQUAKE_JSON) != null) {
			entry = gson.fromJson(getArguments().getString(CONSTANTS.EARTHQUAKE_JSON), EarthquakeEntry.class);
		}
		if (entry == null) entry = new EarthquakeEntry();
        return entry;
    }
	
	private void setText(EarthquakeEntry entry, View view) {
		if (entry.getUpdated() != null) {
			TextView textView = (TextView) view.findViewById(R.id.text_detail);
			textView.setText(entry.getTitle());
			TextView whenHappenedView = (TextView) view.findViewById(R.id.text_when_happened);
			SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");
			whenHappenedView.setText(format.format(entry.getUpdated()));
			WebView webView = (WebView) view.findViewById(R.id.text_webview);
			webView.loadData(entry.getSummary().getSummary(), "text/html", null);
			view.invalidate();
		}
	}
	
	public void setText(EarthquakeEntry entry) {
		setText(entry, getView());
	}
}